﻿using LD.Host;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace LD.BC
{
    public class SoundHelper
    {
        private Timer timer;
        private object obj = new object();
        private static SoundHelper instance;
        public static SoundHelper Instance
        {
            private set { instance = value; }
            get
            {
                if (instance == null)
                    instance = new SoundHelper();
                return instance;
            }
        }
        private TB_IO Sound { get; set; }
        public void Signal(LevelType signal)
        {

            Sound = BcFactory.Instance.Config.IoList
                            .Where(p => p.IoType == (int)IoType.输出 && p.FixType == LightEnum.蜂鸣.ToString())
                            .FirstOrDefault();
            if (Sound != null)
            {
                if (signal == LevelType.低电平)
                {
                    if ((bool)Cache.GetCache(CONST.BC_ERRORING))
                        return;
                    Cache.SetCache(CONST.BC_ERRORING, true);
                    lock (obj)
                    {
                        if (timer == null)
                        {
                            timer = new Timer(1000);
                            timer.Elapsed += Timer_Elapsed;
                        }
                        timer.Start();
                    }
                }
                else if (signal == LevelType.高电平)
                {
                    if (timer != null)
                    {
                        timer.Enabled = false;
                        timer.Dispose();
                        timer = null;
                    }
                    Cache.SetCache(CONST.BC_ERRORING, false);
                    BcFactory.Instance.StartStop.Light(LightEnum.红灯, LevelType.高电平);
                    BcFactory.Instance.StartStop.Sound(LevelType.高电平);
                }
            }

        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            timer.Stop();
            BcFactory.Instance.StartStop.ClosedLight();
            BcFactory.Instance.StartStop.Light(LightEnum.红灯, LevelType.低电平);
            if ((bool)Cache.GetCache(CONST.BC_SOUND))
                BcFactory.Instance.StartStop.Sound(LevelType.低电平);

            Task.Delay(500).Wait();

            BcFactory.Instance.StartStop.Light(LightEnum.红灯, LevelType.高电平);
            BcFactory.Instance.StartStop.Sound(LevelType.高电平);
            Task.Delay(500).Wait();

            if (timer != null)
                timer.Start();
        }
    }
}
